package com.crt.nexus.security.util;

import com.crt.nexus.security.domain.bean.ClientBean;
import com.google.common.base.Strings;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.BadCredentialsException;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static com.crt.nexus.core.constant.SecurityConstants.BASIC_;
import static com.crt.nexus.core.constant.SecurityConstants.GRANT;

@UtilityClass
public class WebUtils extends org.springframework.web.util.WebUtils {

    /**
     * 从request 获取CLIENT_ID
     */
    public ClientBean getClient(HttpServletRequest request) {
        String grant = request.getParameter(GRANT);
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (Strings.isNullOrEmpty(header) || !header.startsWith(BASIC_)) {
            throw new BadCredentialsException("未知的客户端授权证书");
        }
        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("解码客户端授权证书失败");
        }
        String token = new String(decoded, StandardCharsets.UTF_8);
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("无效的客户端授权证书");
        }
        return ClientBean.builder()
                .clientId(token.substring(0, delim))
                .clientSecret(token.substring(delim + 1))
                .grantType(grant)
                .build();
    }

}
